<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Expressions in Tcl</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Tcl, learn Tcl, expressions, programming, language,">
<meta name="description" content="In this chapter of the Tcl tutorial, we cover expressions.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Expressions in Tcl</h1>

<p>
In this part of the Tcl tutorial, we will talk about expressions.
In Tcl language the expressions are not built into the core language. 
Expressions are evaluated with the <code>expr</code> command. 
</p>

<p>
Expressions are constructed from operands and operators. The operators of 
an expression indicate which operations to apply to the operands. 
The order of evaluation of operators in an expression is determined by the 
<b>precedence</b> and <b>associativity</b> of the operators.
</p>

<p>
An <b>operator</b> is a special symbol which indicates 
a certain process is carried out. Operators in programming languages are 
taken from mathematics. Programmers work with data. The operators are used 
to process data. An <b>operand</b> is one of the inputs 
(arguments) of an operator.
</p>

<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* LargeSquare */
google_ad_slot = "5070696322";
google_ad_width = 336;
google_ad_height = 280;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>

<p>
The following table shows a set of operators used in the Tcl language.
</p>

<table> 
  <tr> 
    <th>Category</th> 
    <th>Symbol</th>
  </tr> 
  <tr> 
    <td>Sign, bit-wise, logical NOT</td>
    <td><code>-  +  ~  !</code></td>     
  </tr> 
  <tr class="gray">
    <td>Exponentiation</td> 
    <td><code>**</code></td> 
  </tr> 
  <tr> 
    <td>Arithmetic</td>
    <td><code>+   -   *   /   %</code></td>     
  </tr> 
  <tr class="gray">
    <td>Shift</td> 
    <td><code>&lt;&lt; &gt;&gt;</code></td> 
  </tr> 
  <tr>
    <td>Relational</td>
    <td><code>==   !=   &lt;   &gt;   &lt;=   &gt;=</code></td> 
  </tr> 
  <tr class="gray">
    <td>String comparison</td>
    <td><code>eq ne</code></td> 
  </tr> 
  <tr>
    <td>List</td>
    <td><code>in ni</code></td> 
  </tr> 
  <tr class="gray"> 
    <td>Bitwise</td> 
    <td><code>&amp;   |   ^</code></td> 
  </tr>
  <tr> 
    <td>Boolean</td> 
    <td><code>&amp;&amp;   ||</code></td> 
  </tr>
  <tr class="gray">
    <td>Ternary</td>
    <td><code>?:</code></td> 
  </tr> 

</table> 

<br>

<p>
An operator usually has one or two operands. Those operators that work 
with only one operand are called <b>unary operators</b>. 
Those which work with two operands are called <b>binary operators</b>. 
There is also one ternary operator (?:), which works with three operands.
</p>


<h2>Basic operators</h2>

<p>
Basic operators are commonly used operators. These are sign operators, arithmetic
operators, modulo and exponentiation operators. 
</p>

<pre class="code">
#!/usr/bin/tclsh

puts [expr +2]
puts [expr -2]
puts [expr -(-2)]
puts [expr 2+2]
puts [expr 2-2]
puts [expr 2*2]
puts [expr 2/2]
puts [expr 2/2.0]
puts [expr 2 % 2]
puts [expr 2 ** 2]
</pre>

<p>
The above example shows usage of common operators in Tcl. 
</p>

<pre class="explanation">
puts [expr +2]
</pre>

<p>
In this code line we use the plus sign operator. It has no effect on
the number. It merely indicates that the number is positive. It can 
be omitted and most of the time it is. 
</p>

<pre class="explanation">
puts [expr -2]
puts [expr -(-2)]
</pre>

<p>
The minus operator is compulsory. It says that the number is negative. 
The minus operator changes the sign of the number. In the second line,
the minus operator changes the -2 to positive 2. 
</p>

<pre class="explanation">
puts [expr 2+2]
puts [expr 2-2]
puts [expr 2*2]
puts [expr 2/2]
</pre>

<p>
The above lines show common arithmetic operators in use. 
</p>

<pre class="explanation">
puts [expr 2 % 2]
</pre>

<p>
The % is the modulo or remainder operator. It finds the remainder of 
division of one number by another. 2 % 2, 2 modulo 2 is 0 because
2 goes into 2 once with the remainder of 0. So the code line prints
zero to the console. 
</p>

<pre class="explanation">
puts [expr 2 ** 2]
</pre>

<p>
This is the exponentiation operator. The code line prints 4 to the
console. 
</p>

<pre>
$ ./exp.tcl
2
-2
2
4
0
4
1
1.0
0
4
</pre>

<p>
Output of the example.
</p>

<h2>Division operator</h2>

<p>
Beginning programmers are often confused by division operation.
In many programming languages there are two kinds of division operations.
Integer and non-integer. This applies for the Tcl as well. 
</p>

<pre class="code">
% expr 3/2
1
% expr 3/2.0
1.5
</pre>

<p>
Note the difference between the integer and floating point division.
When at least one of the operands is a floating point number, the result is 
a floating point value too. The result is more exact. If both operands
are integers, the result is an integer too. 
</p>


<h2>Assignment operator, increment operator</h2>


<p>
There is no assignment operator (=) and no increment/decrement (++/--) operators
in Tcl. These operators are common in other computer languages. 
Instead of that, Tcl has commands. 
</p>

<pre class="code">
% set a 5
5
% incr a  
6
% incr a
7
% incr a -1
6
</pre>

<p>
The above code shows what commands are used to implement the missing
operators. 
</p>

<pre class="code">
% set a 5
</pre>

<p>
In Python, we would do <code>a = 5</code>. In Tcl, we set a value to 
a variable using the <code>set</code> command. 
</p>

<pre class="code">
% incr a  
6
</pre>

<p>
In C, Java and many other languages, we would increment a variable by
one this way: <code>a++;</code>. In Tcl, we use the <code>incr</code>
command. By default, the value is incremented by 1. 
</p>

<pre class="code">
% incr a -1
6
</pre>

<p>
The above code shows how to decrement a variable by one, which is
accomplished commonly by the (--) decrement operator in other languages.
</p>

<h2>Boolean operators</h2>

<p>
In Tcl, we have the following logical operators. 
Boolean operators are also called logical. 
</p>

<table>
<tr>
<th>Symbol</th><th>Name</th>
</tr>
<tr><td>&amp;&amp;</td><td>logical and</td></tr>
<tr class="gray"><td>||</td><td>logical or</td></tr>
<tr><td>!</td><td>negation</td></tr>
</table>

<pre class="code">
#!/usr/bin/tclsh

set x 3
set y 8

puts [expr $x == $y]
puts [expr $y > $x]

if {$y > $x} {

    puts "y is greater than x"
}
</pre>

<p>
Many expressions result in a boolean value. Boolean values are used
in conditional statements. 
</p>

<pre class="explanation">
puts [expr $x == $y]
puts [expr $y > $x]
</pre>

<p>
Relational operators always result in a boolean value. These two lines
print 0 and 1. 
</p>

<pre class="explanation">
if {$y > $x} {

    puts "y is greater than x"
}
</pre>

<p>
The body of the <code>if</code> command is executed only if the condition 
inside the parentheses is met. The $y > $x returns true, so the message 
"y is greater than x" is printed to the terminal. 
</p>

<hr class="btm">

<pre class="code">
#!/usr/bin/tclsh

puts [expr 0 &amp;&amp; 0]
puts [expr 0 &amp;&amp; 1]
puts [expr 1 &amp;&amp; 0]
puts [expr 1 &amp;&amp; 1]
</pre>

<p>
Example shows the logical and (&amp;&amp;) operator. 
It evaluates to true only if both operands are true.
</p>

<pre>
$ ./andoperator.tcl 
0
0
0
1
</pre>

<hr class="btm">

<p>
The logical or (||) operator evaluates to true, 
if either of the operands is true.
</p>

<pre class="code">
#!/usr/bin/tclsh

puts [expr 0 || 0]
puts [expr 0 || 1]
puts [expr 1 || 0]
puts [expr 1 || 1]
</pre>

<p>
If one of the sides of the operator is true, the outcome of 
the operation is true. 
</p>

<pre>
$ ./oroperator.tcl 
0
1
1
1
</pre>

<hr class="btm">

<p>
The negation operator (!) makes true false and false true. 
</p>

<pre class="code">
#!/usr/bin/tclsh

puts [expr ! 0]
puts [expr ! 1]
puts [expr ! (4&lt;3)]
</pre>

<p>
The example shows the negation operator in action.
</p>

<pre>
$ ./not.tcl 
1
0
1
</pre>

<hr class="btm">

<p>
The <code>||</code>, and <code>&amp;&amp;</code> operators 
are short circuit evaluated. <b>Short circuit evaluation</b> means 
that the second argument is only evaluated if the first argument does 
not suffice to determine the value of the expression: when the first 
argument of the logical and evaluates to false, the overall value must
be false; and when the first argument of logical or evaluates to true, 
the overall value must be true. (wikipedia)
Short circuit evaluation is used mainly to improve performance. 
</p>

<p>
An example may clarify this a bit more.  
</p>

<pre class="code">
#!/usr/bin/tclsh


proc One {} {
    
    puts "Inside one"
    return false
}

proc Two {} {

    puts "Inside two"
    return true
}

puts "Short circuit"

if { [One] &amp;&amp; [Two] } {

    puts "Pass"
}

puts "###################"

if { [Two] || [One] } {

    puts "Pass"
}
</pre>

<p>
We have two procedures in the example. (Procedures and conditionals will be described
later.) They are used as operands in boolean expressions. We will see, 
if they are called or not.
</p>

<pre class="explanation">
if { [One] &amp;&amp; [Two] } {

    puts "Pass"
}
</pre>

<p>
The One procedure returns false. The short circuit &amp;&amp;
does not evaluate the second procedure. It is not necessary.
Once an operand is false, the result of the logical conclusion is always
false. Only "Inside one" is only printed to the console. 
</p>

<pre class="explanation">
puts "###################"

if { [Two] || [One] } {

    puts "Pass"
}
</pre>

<p>
In the second case, we use the || operator and use the Two
procedure as the first operand.
In this case, "Inside two" and "Pass" strings are printed to
the terminal. It is again not necessary to evaluate the second
operand, since once the first operand evaluates to true, the 
logical or is always true.
</p>


<pre>
$ ./shortcircuit.tcl
Short circuit
Inside one
###################
Inside two
Pass
</pre>

<p>
Result of the shorcircuit.tcl script.
</p>


<h2>Relational Operators</h2>

<p>
Relational operators are used to compare values. These operators always 
result in boolean value. In Tcl 0 stands for false and 1 for true.
Relational operators are also called comparison operators.
</p>

<table>
<tr>
<th>Symbol</th><th>Meaning</th>
</tr>
<tr><td>&lt;</td><td>less than</td></tr>
<tr class="gray"><td>&lt;=</td><td>less than or equal to</td></tr>
<tr><td>&gt;</td><td>greater than</td></tr>
<tr class="gray"><td>&gt;=</td><td>greater than or equal to</td></tr>
<tr><td>==</td><td>equal to</td></tr>
<tr class="gray"><td>!=</td><td>not equal to</td></tr>
</table>

<pre class="code">
#!/usr/bin/tclsh

puts [expr 3 &lt; 4]
puts [expr 3 == 4]
puts [expr 4 &gt;= 3]
puts [expr 4 != 3]
</pre>

<p>
In Tcl we use the == to compare numbers. Some languages
like Ada, Visual Basic, or Pascal use = for comparing numbers.
</p>

<pre>
$ ./rel.tcl
1
0
1
1
</pre>

<p>
The example prints four boolean values. 
</p>


<h2>Bitwise operators</h2>

<p>
Decimal numbers are natural to humans. Binary numbers are native to computers. 
Binary, octal, decimal or hexadecimal symbols are only notations of the same number. 
Bitwise operators work with bits of a binary number. Bitwise operators are seldom 
used in higher level languages like Tcl. 
</p>

<table>
<tr>
<th>Symbol</th><th>Meaning</th>
</tr>
<tr><td>~</td><td>bitwise negation</td></tr>
<tr class="gray"><td>^</td><td>bitwise exclusive or</td></tr>
<tr><td>&amp;</td><td>bitwise and</td></tr>
<tr class="gray"><td>|</td><td>bitwise or</td></tr>
</table>

<p>
The <b>bitwise negation operator</b> changes each 1 to 0 and 0 to 1. 
</p>

<pre class="code">
% puts [expr ~7] 
-8
% puts [expr ~-8]
7
</pre>

<p>
The operator reverts all bits of a number 7. One of the bits also determines, 
whether the number is negative or not. If we negate all the bits one more 
time, we get number 7 again. 
</p>

<p>
The <b>bitwise and operator</b> performs bit-by-bit comparison between two numbers. 
The result for a bit position is 1 only if both corresponding bits in the operands are 1. 
</p>

<pre>
      00110
   &amp;  00011
   =  00010
</pre>

<p>
The first number is a binary notation of 6. The second is 3. The result is 2. 
</p>

<pre class="code">
% puts [expr 6 &amp; 3]
2
% puts [expr 3 &amp; 6]
2
</pre>

<p>
The <b>bitwise or operator</b> performs bit-by-bit comparison between two numbers. 
The result for a bit position is 1 if either of the corresponding bits in the operands is 1. 
</p>

<pre>
     00110
   | 00011
   = 00111
</pre>

<p>
The result is <code>00110</code> or decimal 7. 
</p>

<pre class="code">
% puts [expr 6 | 3]
7
% puts [expr 3 | 6]
7
</pre>

<p>
The <b>bitwise exclusive or operator</b> performs bit-by-bit comparison between two numbers. 
The result for a bit position is 1 if one or the other (but not both) of the 
corresponding bits in the operands is 1. 
</p>

<pre>
      00110
   ^  00011
   =  00101
</pre>

<p>
The result is <code>00101</code> or decimal 5. 
</p>

<pre class="code">
% puts [expr 6 ^ 3]
5
% puts [expr 3 ^ 6]
5
</pre>


<h2>Operator precedence</h2>

<p>
The <b>operator precedence</b> tells us which operators are evaluated first. 
The precedence level is necessary to avoid
ambiguity in expressions. 
</p>

<p>
What is the outcome of the following expression? 28 or 40?
</p>

<pre>
 3 + 5 * 5
</pre>

<p>
Like in mathematics, the multiplication operator has a higher 
precedence than addition operator. So the outcome is 28.
</p>

<pre>
(3 + 5) * 5
</pre>

<p>
To change the order of evaluation, we can use parentheses.
Expressions inside parentheses are always evaluated first. 
</p>


<p>
The following table shows common Tcl operators ordered by
precedence (highest precedence first):
</p> 

<table> 
  <tr> 
    <th>Category</th> 
    <th>Symbol</th>
    <th>Associativity</th>
  </tr> 
  <tr> 
    <td>Sign, bit-wise, logical NOT</td>
    <td><code>-  +  ~  !</code></td>     
    <td>Left</td> 
  </tr> 
  <tr class="gray">
    <td>Exponentiation</td> 
    <td><code>**</code></td>
    <td>Left</td>  
  </tr> 
  <tr> 
    <td>Arithmetic</td>
    <td><code>+   -   *   /   %</code></td>     
    <td>Left</td> 
  </tr> 
  <tr class="gray">
    <td>Shift</td> 
    <td><code>&lt;&lt; &gt;&gt;</code></td> 
    <td>Left</td> 
  </tr> 
  <tr>
    <td>Relational</td>
    <td><code>==   !=   &lt;   &gt;   &lt;=   &gt;=</code></td> 
    <td>Left</td> 
  </tr> 
  <tr class="gray">
    <td>String comparison</td>
    <td><code>eq ne</code></td> 
    <td>Left</td> 
  </tr> 
  <tr>
    <td>List</td>
    <td><code>in ni</code></td> 
    <td>Left</td> 
  </tr> 
  <tr class="gray"> 
    <td>Bitwise</td> 
    <td><code>&amp;   |   ^</code></td> 
    <td>Left</td> 
  </tr>
  <tr> 
    <td>Boolean</td> 
    <td><code>&amp;&amp;   ||</code></td> 
    <td>Left</td> 
  </tr>
  <tr class="gray">
    <td>Ternary</td>
    <td><code>?:</code></td> 
    <td>Right</td> 
  </tr> 

</table> 
 

<p>
Operators on the same row of the table have the same precedence.
</p> 

<pre class="code">
!/usr/bin/tclsh

puts [expr 3 + 5 * 5]
puts [expr (3 + 5) * 5]

puts [expr ! 1 || 1]
puts [expr ! (1 || 1)]
</pre>

<p>
In this code example, we show some common expressions. 
The outcome of each expression is dependent on the precedence level.
</p>

<pre class="explanation">
puts [expr 3 + 5 * 5]
</pre>

<p>
This line prints 28. The multiplication operator has a higher precedence
than addition. First the product of 5*5 is calculated. Then 3 is added. 
</p>

<pre class="explanation">
puts [expr (3 + 5) * 5]
</pre>

<p>
Round brackets can be used to change the precedence level. In the above 
expression, number 3 is added to 5 and the result is multiplied by 5. 
</p>


<pre class="explanation">
puts [expr ! 1 || 1]
</pre>

<p>
In this case, the negation operator has a higher precedence. First, 
the first true (1) value is negated to false (0), than the || operator 
combines false and true, which gives true in the end. 
</p>

<pre>
$ ./precedence.tcl 
28
40
1
0
</pre>

<p>
Output.
</p>


<h2>Associativity</h2>

<p>
Sometimes the precedence is not satisfactory to determine the outcome 
of an expression. There is another rule called
<b>associativity</b>. The associativity of operators determines 
the order of evaluation of operators with the <b>same</b>
precedence level. 
</p>

<pre>
9 / 3 * 3
</pre>

<p>
What is the outcome of this expression? 9 or 1? The multiplication, 
deletion and the modulo operator are left to right associated. 
So the expression is evaluated this way: <code>(9 / 3) * 3</code> 
and the result is 9.
</p>

<p>
Arithmetic, boolean, relational and bitwise operators are all left 
to right associated. 
</p>

<p>
The ternary operator is right associated. 
</p>


<h2>The ternary operator</h2>

<p>
The ternary operator (?:) is a conditional operator. It is a convenient
operator for cases, where we want to pick up one of two values, depending
on the conditional expression.
</p>

<pre>
cond-exp ? exp1 : exp2
</pre>

<p>
If cond-exp is true, exp1 is evaluated and the result is returned. If
the cond-exp is false, exp2 is evaluated and its result is returned.
</p>

<pre class="code">
#!/usr/bin/tclsh

set age 32
set adult [expr $age >= 18 ? true : false]

puts "Adult: $adult"
</pre>

<p>
In most countries the adulthood is based on your age.
You are adult if you are older than a certain age.
This is a situation for a ternary operator.
</p>

<pre class="explanation">
set adult [expr $age >= 18 ? true : false]
</pre>

<p>
First the expression on the right side of the assignment
operator is evaluated. The first phase of the ternary operator
is the condition expression evaluation. So if the age is greater
or equal to 18, the value following the ? character is returned.
If not, the value following the : character is returned.
The returned value is then assigned to the adult variable.
</p>

<pre>
$ ./ternary.tcl
Adult: true
</pre>

<p>
A 32 years old person is adult.
</p>


<h2>Calculating prime numbers</h2>

<p>
We are going to calculate prime numbers. Some of the features
(lists, loops) will be covered later in the tutorial.
</p>

<pre class="code">
#!/usr/bin/tclsh

set nums { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 
    15 16 17 18 19 20 21 22 23 24
}

puts "Prime numbers"

foreach num $nums {

    if { $num==1 || $num==2 || $num==3 } {

        puts -nonewline "$num " 
        continue
    }

    set i [expr int(sqrt($num))]
    set isPrime true

    while { $i > 1 } {

        if { $num % $i == 0 } {

            set isPrime false
        }

        incr i -1
    }

    if { $isPrime } {
          
        puts -nonewline "$num "
    }
}
 
puts ""
</pre>

<p>
In the above example, we deal with many various operators. A prime 
number (or a prime) is a natural number that has exactly two distinct 
natural number divisors: 1 and itself. We pick up a number and divide 
it by numbers, from 1 up to the picked up number. Actually, we don't have
to try all smaller numbers, we can divide by numbers up to the square
root of the chosen number. The formula will work. We use the remainder 
division operator. 
</p>

<pre class="explanation">
set nums { 1 2 3 4 5 6 7 8 9 10 11 12 13 14 
    15 16 17 18 19 20 21 22 23 24
}
</pre>

<p>
We will calculate primes from this list of numbers. 
</p>

<pre class="explanation">
if { $num==1 || $num==2 || $num==3 } {

    puts -nonewline "$num " 
    continue
}
</pre>

<p>
We skip the calculations for the 1, 2, 3 numbers. They
are primes. Note the usage of the equality and conditional or
operators. The == has a higher precedence than the || operator.
So we don't need to use parentheses.
</p>

<pre class="explanation">
set i [expr int(sqrt($num))]
</pre>

<p>
We are OK if we only try numbers smaller than the square root of
a number in question. 
</p>

<pre class="explanation">
while { $i > 1 } {

    if { $num % $i == 0 } {

        set isPrime false
    }

    incr i -1
}
</pre>

<p>
This is a while loop. The i is the calculated square root
of the number. We use the <code>incr</code> command to 
to decrease the i by one each loop cycle. When the i is smaller than
1, we terminate the loop. For example, we have number 9.
The square root of 9 is 3. We will divide the 9 number by
3 and 2. This is sufficient for our calculation.
</p>

<pre class="explanation">
if { $isPrime } {
      
    puts -nonewline "$num "
}
</pre>

<p>
This is the core of the algorithm. If the remainder division
operator returns 0 for any of the i values, than the number in
question is not a prime.
</p>

<pre>
$ ./prime.tcl
Prime numbers
1 2 3 5 7 11 13 17 19 23 
</pre>

<p>
Output of the script.
</p>

<p>
In this part of the Tcl tutorial, we covered expressions. 
</p>

<br>
<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div> 
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified April 8, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

